package com.hzb.shop.autocode.sql;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class TableSchme {

	public static void main(String[] args) {
		test();
	}
	public static void test(){
		Connection con = ConnectionUtil.getConnection("jdbc:mysql://192.168.45.129:3306/hzb.shop?characterEncoding=utf-8", "root", "houzhangbo");
		try {
			DatabaseMetaData dm = con.getMetaData();
//			ResultSet rs = dm.getTables("hncu", "hncu", null, new String[]{"TABLE","VIEW"} );
//			while(rs.next()){
//			String name = rs.getString("TABLE_NAME"); //字符串参数的具体取值参看API中getTables()
//			String name2 = rs.getString("TABLE_TYPE");
//			System.out.println(name+","+name2);
//			}
			
			String sql = "select * from " + "shop_user";

			ResultSet rs = con.createStatement().executeQuery(sql);
			ResultSetMetaData rsmd = rs.getMetaData();

			//获取当前表格的列数
			int columns = rsmd.getColumnCount();
			System.out.println("列数:"+columns);

			//输出当前表格的表头
			System.out.println("------------------");
			for(int i=0; i<columns;i++){
				System.out.println(rsmd.getColumnName(i+1)+"\t");
				System.out.println(rsmd.getColumnTypeName(i+1)+"\t");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	public static List<TableColumn> getColumns(String url,String user,String pwd,String tableName){
		List<TableColumn> list = new ArrayList<TableColumn>();
		Connection con = ConnectionUtil.getConnection(url,user,pwd);
		String sql = "select * from " + tableName;
		ResultSet rs = null;
		Statement st = null;
		try {
			st = con.createStatement();
			rs = st.executeQuery(sql);
			ResultSetMetaData rsmd = rs.getMetaData();
			//获取当前表格的列数
			int columns = rsmd.getColumnCount();
			//输出当前表格的表头
			for(int i=0; i<columns;i++){
				list.add(new TableColumn(rsmd.getColumnName(i+1),rsmd.getColumnTypeName(i+1)));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				st.close();
				rs.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
}
